package models

import (
	"github.com/astaxie/beego/orm"
	"time"
	"github.com/toolkits/web"
	"fmt"
	"net/http"
)

type User struct {
	Id         int64 `form:"-" json:"id"`
	Username   string `form:"username" json:'username`
	Password   string `form:"password" json:'password`
	CreateDate time.Time `form:"create_date" json:"create_date"`
	UpdateDate time.Time `form:"update_date" json:"update_date"`
}

type BaseDao struct {

}

type UserDao struct {
	BaseDao
}

func (userDao *UserDao) Page(request *http.Request, size int, query string) ([]User, *web.Paginator) {
	qs := orm.NewOrm().QueryTable(new(User))
	if query != "" {
		qs.Filter("username__icontains", query)
	}

	total, err := qs.Count()
	if err != nil {
		fmt.Print("error")
		return nil, nil
	}

	pager := web.NewPaginator(request, size, total)
	qs = qs.Limit(size, pager.Offset())

	var us []User
	_, err = qs.All(&us)
	if err != nil {
		fmt.Print("error")
		return nil, nil
	}

	return us, pager
}

func (userDao *UserDao) Get(id int64) *User {
	if id <= 0 {
		return nil
	}

	u := User{Id: id}
	err := orm.NewOrm().Read(&u)
	if err != nil {
		return nil
	}

	return &u
}

func (userDao *UserDao) Insert(user *User) (int64, error) {
	return orm.NewOrm().Insert(user)
}

func (userDao *UserDao) Update(user *User) {
	orm.NewOrm().Update(user, "Username")
}

func (userDao *UserDao) Delete(id int64) {
	orm.NewOrm().Delete(&User{Id:id})
}